const nfetch = require("node-fetch");
const cfetch = require("fetch-cookie")(nfetch);
const Bluebird = require("bluebird");
nfetch.Promise = Bluebird;

const baseUrl = "http://api.zqd.com";

export default async function efetch(
  url: string = "",
  data: any = {},
  type = "GET",
  resType: any = "JSON"
) {
  type = type.toUpperCase();
  resType = resType.toUpperCase();
  if (type == "GET") {
    let dataStr = ""; //数据拼接字符串
    Object.keys(data).forEach(key => {
      dataStr += key + "=" + data[key] + "&";
    });

    if (dataStr !== "") {
      dataStr = dataStr.substr(0, dataStr.lastIndexOf("&"));
      url = url + "?" + dataStr;
    }
  }

  let requestConfig: any = {
    method: type,
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json"
    }
  };

  if (type == "POST") {
    Object.defineProperty(requestConfig, "body", {
      value: JSON.stringify(data)
    });
  }
  let responseJson;
  try {
    const response = await cfetch(`${baseUrl}/${url}`, requestConfig);
    // console.log("req", `${baseUrl}/${url}`, requestConfig.body);
    if (resType === "TEXT") {
      responseJson = await response.text();
    } else {
      responseJson = await response.json();
    }
    // console.log("res", responseJson);
  } catch (err) {
    console.log("获取http数据失败", err);
    throw new Error(err);
  }
  return responseJson;
}
